﻿using System;
using System.Linq;
using System.Windows.Forms;
using TestSystem.DataManipulation;
using TestSystem.Model;
using TestSystem.Model.Data.Repositories;
using TestSystem.Model.Exceptions;
using TestSystem.Model.Resources;
using TestSystem.Ui.Controls;
using TestSystem.Ui.Forms;
using TestSystem.Ui.Helpers;

namespace TestSystem.Ui
{
    public partial class MainForm
    {
        #region Initialization

        private void InitializeFormData()
        {
            InitializeFolders();

        }

        private void InitializeFolders()
        {

            var folders = Program.Model.GetAllFolders();

            var frequencyTypes = Program.Model.GetFrequencyTypes();
            foreach (var folder in folders)
            {
                var node = folder.ToTreeNode();
                node.ContextMenuStrip = FoldersContextMenu;
                foreach (var currentTool in folder.Tools.Select(tool => tool.ToTreeNode()))
                {
                    currentTool.ImageIndex = 1;
                    currentTool.SelectedImageIndex = 1;
                    node.Nodes.Add(currentTool);
                    
                    node.LastNode.ContextMenuStrip = ToolsContextMenu;
                    var xxx = frequencyTypes.Select(frequencyType => frequencyType.ToTreeNode());
                    if (node.Nodes.Count != 0)
                        foreach (var currentNode in frequencyTypes.Select(frequencyType => frequencyType.ToTreeNode()))
                        {
                            currentNode.ImageIndex = 6;
                            currentNode.SelectedImageIndex = 6;
                            currentNode.ContextMenuStrip = FreqContextMenu;
                            node.LastNode.Nodes.Add(currentNode);
                        }
                }

                treeViewData.Nodes.Add(node);
                SetControlsProperties();
            }

        }

        #endregion

    
        private void CreateNewFolder()
        {
            var dialog = new GetFolderForm();
            var result = dialog.ShowDialog("Create Folder", "Set name of the Folder:");
            treeViewData.ImageList = treeImageList;
            if (result == DialogResult.OK)
            {
                try
                {
                    var folder = Program.Model.CreateNewFolder(dialog.Value);
                    var currentFolder = folder.ToTreeNode();
                    currentFolder.ContextMenuStrip = FoldersContextMenu;
                    treeViewData.Nodes.Add(currentFolder);

                }
                catch (EntityAlreadyExistsException)
                {
                    MessagingHelper.ShowError(Strings.ItemAlreadyExists);
                }
            }

        }
        private void CreateNewTool()
        {
            var selectedNode = treeViewData.SelectedNode;
            for (var i = 0; !(selectedNode is FolderTreeNode) && i < 10; i++)
                selectedNode = selectedNode.Parent;

            var parentId = (Int32)selectedNode.Tag;
            var dialog = new GetToolForm();
            
            var result = dialog.ShowDialog("Create Tool", "Set name of the Tool:", "Set description of the Tool:");
            if (result == DialogResult.OK)
            {
                try
                {
                    var tool = Program.Model.CreateNewToolFor(parentId, dialog.Value, dialog.Description);
                    var node = tool.ToTreeNode();
                    node.ContextMenuStrip = ToolsContextMenu;
                    buttonImportData.ContextMenuStrip = ToolsContextMenu;


                    node.ImageIndex = 1;
                    node.SelectedImageIndex = 1;
                    selectedNode.Nodes.Add(node);
                    var frequencyTypes = Program.Model.CreateFrequencyTypesForTool(tool.Id);
                    foreach (var freqnode in frequencyTypes.Select(currentNode => currentNode.ToTreeNode()))
                    {
                        freqnode.ImageIndex = 6;
                        freqnode.SelectedImageIndex = 6;
                        freqnode.ContextMenuStrip = FreqContextMenu;
                        node.Nodes.Add(freqnode);
                    }


                }
                catch (NoSuchEntityException)
                {
                    MessagingHelper.ShowError(Strings.NoSuchParentItem);
                }
            }
        }

        private void DeleteSelectedNode()
        {
            var selectedNode = treeViewData.SelectedNode;
            if (MessageBox.Show
                (@"Are you sure you want to delete " + selectedNode.Text + @"?",
                @"Test System", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.Cancel)
            {
                if (selectedNode is ToolTreeNode)
                {
                    Program.Model.DeleteToolFromFolder((Int32)selectedNode.Tag);
                    treeViewData.Nodes.Remove(selectedNode);
                }
                if (selectedNode is FolderTreeNode)
                {
                    Program.Model.DeleteFolder((Int32)selectedNode.Tag);
                    treeViewData.Nodes.Remove(selectedNode);
                }
         
            }
            tsbRemove.Enabled = treeViewData.Nodes.Count != 0;
            tsbCreateTool.Enabled = treeViewData.Nodes.Count != 0;
        }
        private void SetControlsProperties()
        {
            tsbRemove.Enabled = treeViewData.Nodes.Count != 0;
            tsbCreateTool.Enabled = treeViewData.Nodes.Count != 0;
            buttonAdd.Enabled = treeViewData.Nodes.Count == 0;
            buttonDelete.Enabled = treeViewData.Nodes.Count == 0;
            buttonEdit.Enabled = treeViewData.Nodes.Count == 0;
        }
        private void RenameSelectedFolder()
        {
            var dialog = new GetFolderForm();
            var result = dialog.ShowDialog("Rename Folder", "Set name of the Folder:", treeViewData.SelectedNode.Text);
            if (result != DialogResult.OK) return;
            var folder = Program.Model.RenameFolder(dialog.Value, (Int32) treeViewData.SelectedNode.Tag);
            treeViewData.SelectedNode.Text = folder.Name;
        }
        private void RenameSelectedTool()
        {
            var dialog = new GetToolForm();
            var toolRepository = new ToolsRepository();
            var currenttool = toolRepository.GetById((Int32) treeViewData.SelectedNode.Tag);
            var result = dialog.ShowDialog("Rename Tool", "Set name of the tool:", 
                "Set description of the tool", currenttool.Name, currenttool.Description);
            if (result == DialogResult.OK)
            {
                var tool = Program.Model.RenameTool(dialog.Value,dialog.Description, (Int32)treeViewData.SelectedNode.Tag);
                treeViewData.SelectedNode.Text = tool.Name + @" (" + tool.Description + @")";
            }
        }

        private QuoteType GetQuoteType()
        {
            return (treeViewData.SelectedNode is FrequencyTreeNode) && (treeViewData.SelectedNode.Text == @"Tick")
                       ? QuoteType.Tick
                       : QuoteType.Bar;
        }
        
        private void DeleteSelectedQuotes()
        {
            var values = (from DataGridViewRow row in DataGrid.SelectedRows select (int) row.Cells[0].Value).ToList();
            foreach (var value in values)
                ModelFacade.DeleteCurrentQuote(value);
                   
          ShowCurrentData();
            
        }

        private void EditSelectedQuote()
        {
            var cells = DataGrid.SelectedCells;
            var quotetype = GetQuoteType();
            if (quotetype == QuoteType.Bar)
            {
                var editbarform = new BarForm();
                editbarform.FormType = FormType.TypeEdit;
                editbarform.DateTimePicker.Value = DateTime.Parse(cells[1].Value.ToString());
                editbarform.OpenValue.Text = cells[2].Value.ToString();
                editbarform.HighValue.Text = cells[3].Value.ToString();
                editbarform.LowValue.Text = cells[4].Value.ToString();
                editbarform.CloseValue.Text = cells[5].Value.ToString();
                editbarform.VolumeValue.Text = cells[6].Value.ToString();
                var result = editbarform.ShowDialog();
                if (result != DialogResult.OK) return;
                ModelFacade.EditCurrentQuote((int)cells[0].Value, editbarform.Quote);
            }
            else
            {
                var edittickform = new TickForm();
                edittickform.FormType = FormType.TypeEdit;
                edittickform.DateTimePicker.Value = DateTime.Parse(cells[1].Value.ToString());
                edittickform.PriceValue.Text = cells[2].Value.ToString();
                edittickform.VolumeValue.Text = cells[3].Value.ToString();
                var result = edittickform.ShowDialog();
                if (result != DialogResult.OK) return;
                ModelFacade.EditCurrentQuote((int)cells[0].Value, edittickform.Quote);

            }
            ShowCurrentData();
        }

        private void AddNewQuote()
        {
            var quotetype = GetQuoteType();
            var toolid = (Int32)treeViewData.SelectedNode.Parent.Tag;
            if (quotetype == QuoteType.Bar)
            {
                var barform = new BarForm();
                barform.FormType = FormType.TypeAdd;
                var result = barform.ShowDialog();
                if (result != DialogResult.OK) return;
                ModelFacade.AddNewQuote(toolid, (Int32)treeViewData.SelectedNode.Tag, (short)quotetype, barform.Quote);

            }

            else
            {
                var tickform = new TickForm();
                tickform.FormType = FormType.TypeAdd;
                var result = tickform.ShowDialog();
                if (result != DialogResult.OK) return;
                ModelFacade.AddNewQuote(toolid, (Int32)treeViewData.SelectedNode.Tag, (short)quotetype, tickform.Quote);
            }
            ShowCurrentData();
        }
    }
}